﻿using AutoMapper;
using MediatR;
using Provenance.Domain.Breed;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Breed;
using Provenance.Read.Api.Application.Command.Breed;

namespace Provenance.Read.Api.Application.CommandHandler.Breed
{
    public class BackBreedInfoCommandHandler : IRequestHandler<BackBreedInfoCommand, ApiResult<BreedingInfo>>
    {
        private readonly IBreedingInfoRepository _breedingInfoRepository;
        private readonly ILogger<BackBreedInfoCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackBreedInfoCommandHandler(IBreedingInfoRepository breedingInfoRepository, ILogger<BackBreedInfoCommandHandler> logger, IMapper mapper)
        {
            _breedingInfoRepository = breedingInfoRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<BreedingInfo>> Handle(BackBreedInfoCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _breedingInfoRepository.GetAsync(x => x.ProductInfoId == request.ProductInfoId);
                if(obj == null)
                {
                    return ApiResult<BreedingInfo>.Failure("Breeding Info not found");
                }
                var result = _mapper.Map<BreedingInfo>(obj);
                return ApiResult<BreedingInfo>.Success(result);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "Error getting breeding info"+ex.Message);
                return ApiResult<BreedingInfo>.Failure("Error getting breeding info"+ex.Message);
            }
        }
    }
}
